package org.tagging.exceptionHandler;

import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.tagging.exception.JwtTokenExpiredAuthenticationException;
import org.tagging.utils.ResponseUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.AccessDeniedException;

@RestControllerAdvice
public class SecurityExceptionHandler implements AuthenticationEntryPoint {

    @ExceptionHandler(AccessDeniedException.class)
    public String accessDeniedException(Exception e) {
        String build = ResponseUtils.build(HttpStatus.BAD_GATEWAY.value(), "无权限！");
        return ResponseUtils.buildJSONString(build);
    }


    @ExceptionHandler(JwtTokenExpiredAuthenticationException.class)
    public String authenticationServiceException(Exception e) {
        String build = ResponseUtils.build(HttpStatus.BAD_GATEWAY.value(), e.getMessage());
        return ResponseUtils.buildJSONString(build);
    }
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        String build = ResponseUtils.build(HttpStatus.BAD_GATEWAY.value(), e.getMessage());
        ResponseUtils.printJson(httpServletResponse, build);
    }


}
